/*
 * @Author: ZAL 2177624751@qq.com
 * @Date: 2025-02-06 09:54:30
 * @LastEditors: ZAL 2177624751@qq.com
 * @LastEditTime: 2025-03-31 17:45:21
 * @FilePath: \asset-management-webc:\Users\21776\Desktop\毕设\shop_app_vue3\store\auth.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { defineStore } from 'pinia'
import { getUserInfo } from '../api/login'
export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: '',
    userInfo: null,
  }),

  getters: {
    isLoggedIn: (state) => !!state.token && !!state.userInfo,
  },

  actions: {
    async login(userInfo) {
      this.token = userInfo.token
      uni.setStorageSync('token', userInfo.token)
      try {
        const res = await getUserInfo()
        if (res.code === 200 && res.data) {
          this.userInfo = res.data
          uni.setStorageSync('userInfo', this.userInfo)
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        // 登录失败时清除token
        this.logout()
      }
    },

    logout() {
      this.token = ''
      this.userInfo = null
      uni.removeStorageSync('token')
      uni.removeStorageSync('userInfo')
    },

    async initFromStorage() {
      const token = uni.getStorageSync('token')
      if (token) {
        this.token = token
        try {
          const res = await getUserInfo()
          if (res.code === 200 && res.data) {
            this.userInfo = res.data
            uni.setStorageSync('userInfo', this.userInfo)
          }
        } catch (error) {
          console.error('初始化获取用户信息失败:', error)
          this.logout() // 获取失败时登出
        }
      }
    },
  },
})
